from datetime import datetime
from django.db import models, IntegrityError, transaction
from django.contrib.gis.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from imagekit.models import ImageModel

class NameSlugModel(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, editable=False)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        """
        Based on the Tag save() method in django-taggit, this method simply
        stores a slugified version of the name, ensuring that the unique
        constraint is observed
        """

        self.slug = slug = slugify(self.name)
        i = 0
        while True:
            try:
                savepoint = transaction.savepoint()
                res = super(NameSlugModel, self).save(*args, **kwargs)
                transaction.savepoint_commit(savepoint)
                return res
            except IntegrityError:
                transaction.savepoint_rollback(savepoint)
                i += 1
                self.slug = '%s_%d' % (slug, i)

class DateAwareModel(models.Model):
    modified_date = models.DateTimeField(auto_now=True)
    created_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

class MyImageModel(ImageModel, NameSlugModel, DateAwareModel):
    image = models.ImageField(upload_to='images')
    num_views = models.PositiveIntegerField(editable=False, default=0)

    class IKOptions:
        spec_module = 'kokoomi.reviews.specs'
        cache_dir = 'cache'
        image_field = 'image'
        save_count_as = 'num_views'
        admin_thumbnail_spec = 'thumbnail'

    class Meta:
        abstract = True
		
    def __unicode__(self):
        return self.slug

class UserOwnedModel(models.Model):
    user = models.ForeignKey(User)

    class Meta:
        abstract = True